const qiniu = require('qiniu');
const http = require("http");

class QiniuClient {
    constructor(cfg){
        this.cfg = cfg;
        this.mac = new qiniu.auth.digest.Mac(cfg.ACCESS_KEY, cfg.SECRET_KEY);
        this.config = new qiniu.conf.Config();
        this.config.zone = qiniu.zone['Zone_z'+cfg.zone];
        this.bucket = cfg.bucket;
        this.credentials = new qiniu.Credentials(cfg.ACCESS_KEY, cfg.SECRET_KEY);
    }

    splitName(path) {
        let offset = path.lastIndexOf("/");
        if (offset > 0) {
            return path.substr(offset+1);
        } else {
            return path;
        }
    }

    getRoomToken(roomName, userName, expire, isAdmin) {
        let roomAccess = {
            appId: this.cfg.appId,
            roomName: roomName,
            userId: userName,
            expireAt: expire,
            permission: isAdmin?'admin':'user'
        };
        return qiniu.room.getRoomToken(roomAccess, this.credentials);
    }

    getFileList(path, ext=null) {
        let self = this;
        let options = {
            prefix: path
        };
        let bucketManager = new qiniu.rs.BucketManager(this.mac, this.config);
        return new Promise(function (resolve, reject) {
            bucketManager.listPrefix(self.bucket, options, function(err, respBody, respInfo) {
                if (err) {
                    reject(err);
                }
                if (respInfo.statusCode == 200) {
                    let arr = [];
                    for (let i = 0; i < respBody.items.length; i++) {
                        if (!ext || respBody.items[i].key.indexOf(ext)!=-1) {
                            arr.push({name:respBody.items[i].key, size:respBody.items[i].fsize});
                        }
                    }
                    resolve(arr);
                } else {
                    reject(respInfo.statusMessage);
                }
            });
        })
    }

    publicDownloadUrl(domain, filename){
        let bucketManager = new qiniu.rs.BucketManager(this.mac, this.config);
        return bucketManager.publicDownloadUrl(domain, filename);
    }

    downloadFile(domain, filename){
        let url = `http://${domain}/${filename}`;
        return new Promise(function (resolve, reject) {
            http.get(url, res=>{
                let str = "";
                res.on('data', function (data) {  
                    str += data;
                });
                res.on("end", function () {  
                    resolve(str);
                });
            }).on("error", err=>{
                reject(err);
            });
        })
    }

    uploadFile(filename, buf){
        let uploadToken = this.uploadToken(filename);
        let formUploader = new qiniu.form_up.FormUploader(this.config);
        let putExtra = new qiniu.form_up.PutExtra();
        return new Promise(function (resolve, reject) {
            formUploader.put(uploadToken, filename, buf, putExtra, function(respErr, respBody, respInfo) {
                if (respErr) {
                    reject(respErr);
                }
                if (respInfo.statusCode == 200) {
                    resolve(respBody);
                } else {
                    reject(respBody);
                }
            });
        })
    }

    uploadToken(filePath){
        let options = {
          scope: `${this.bucket}:${filePath}`
        }
        let putPolicy = new qiniu.rs.PutPolicy(options);
        return putPolicy.uploadToken(this.mac);
    }
}

module.exports = QiniuClient;

// const cfg = {
//     ACCESS_KEY: '',
//     SECRET_KEY: '',
//     appid: '',
//     zone: '2',
//     bucket: ''
// }